import React, {PureComponent} from 'react';
// import { connect } from 'dva';
import style from "styled-components";
import {Form, Input, Button, Menu, Icon, Tree, Select, message, Modal} from 'antd';
import {
  systemComDepartList,
  systemComDepartSave,
  systemComDepartBatchInsertDepart,
  systemComDepartDelete,
} from "../../../services/api";
import bcx_utils from "../../../common/bcx_utils";

const TreeNode = Tree.TreeNode;
const Option = Select.Option;

//转换antd需要的字段
const changeObj = data => {
  let newArr = JSON.parse(JSON.stringify(data));
  newArr.map(({departId, departName, haveChild}, key) => {
    newArr[key] = {
      key: departId,
      title: departName,
      isLeaf: !haveChild,
    };
  });
  return newArr;
}

//转换接口需要的字段
const reverseObj = data => {
  let newArr = JSON.parse(JSON.stringify(data));
  newArr.map(({key, title}, index) => {
    newArr[index] = {
      departId: key,
      departName: title,
    };
  });
  return JSON.stringify(newArr);
}


/**
 * 组建部门机构
 */
export default class InitialDepartmentalInstitutions extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      // count: 0,
      uuid: 1,
      placeholder: '请输入内容',
      header: '百川信（厦门）网络服务信息有限公司',
      caption: '经营管理中心',
      treeData: [],
      currentInfos: {     //当前树节点完整信息
        selectedKey: "",
        dataRef: {
          children: []
        }
      },//当前记录
      currentNode: {},//保存当前节点信息，可以通过这里，直接操作树节点
      expandedKeys: ["-1"],
    };

  }

  /******************************生命周期******************************/

  componentDidMount = () => {
    this.systemComDepartList(-1);
  }
  /******************************ajax请求******************************/
    // 初始化  查询下级部门功能
  systemComDepartList = (parentDepartId) => {
    systemComDepartList({parentDepartId}).then(
      ({data}) => {
        console.log(data);
        //数组第一个为公司名称，其他为第二级别
        let treeData;
        if (data.length === 1) {
          treeData = [{
            key: "-1",
            title: data[0].companyName,
            isLeaf: true,
          }];
        } else {
          let newData = bcx_utils.jsoncopy(data);
          newData.shift();
          //如果没有二级菜单
          if (newData.length === 0) {
            treeData = [{
              key: "-1",
              title: data[0].companyName,
              isLeaf: true,
            }];
          } else {
            treeData = [{
              key: "-1",
              title: data[0].companyName,
              isLeaf: false,
              children: changeObj(newData)
            }];
            //初始化右侧区域
            const currentInfos = this.state.currentInfos;
            currentInfos.dataRef.children = changeObj(newData);
            currentInfos.dataRef.title = data[0].companyName;
            this.setState({currentInfos});
          }
        }
        this.setState({treeData});
      },
      (err) => {
        console.log(err);
      }
    );
  }

  //批量新增部门
  systemComDepartBatchInsertDepart = (ajaxData) => {
    systemComDepartBatchInsertDepart(ajaxData).then(
      ({msg}) => {
        message.success(msg);
        //操作成功，本地更新节点
        this.upDateNode();
      },
      (err) => {
        console.log(err);
      }
    );
  }
  /******************************相关事件******************************/
    //找到节点 更新节点  (提交确认按钮)
  upDateNode = () => {
    const treeData = JSON.parse(JSON.stringify(this.state.treeData));
    const {props: {pos, dataRef: {key}}} = this.state.currentNode;//当前节点的id（key）,还有位置信息
    const [, ...posDetail] = pos.split("-");
    const length = posDetail.length;
    //请求新节点信息，更新旧节点
    systemComDepartList({parentDepartId: key}).then(
      ({data}) => {
        //找到对应节点，更新children
        posDetail.reduce((acc, elem, index) => {
          if ((length - 1) === index) {
            acc[elem].children = changeObj(data).filter(val => val.title !== "");
            this.setState({treeData});
          } else {
            return acc[elem].children;
          }
        }, treeData);
      },
      (err) => {
        console.log(err);
      }
    );
  }
  //删除
  remove = (index, item) => {
    const currentInfos = {...this.state.currentInfos};
    if (item.key !== "") {
      Modal.confirm({
        title: '确认删除该记录?',
        content: '',
        onOk: () => {
          console.log('OK');
          systemComDepartDelete({departId: item.key}).then(
            (data) => {
              message.success(data.msg);
              debugger
              //更新右侧
              // const newArr = currentInfos.dataRef.children.filter((val, key) => key !== index);
              // currentInfos.dataRef.children = newArr;
              // this.setState({currentInfos});
              //更新左侧
              const [, ...posDetail] = this.state.currentNode.props.pos.split("-");
              const treeData = JSON.parse(JSON.stringify(this.state.treeData));
              posDetail.reduce((acc, elem, index) => {
                if ((posDetail.length - 1) === index) {
                  acc[elem].children = newArr;
                  this.setState({treeData});
                } else {
                  return acc[elem].children;
                }
              }, treeData);
            },
            (err) => {
              console.log(err);
            }
          );
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    } else {
      const newArr = currentInfos.dataRef.children.filter((val, key) => key !== index);
      currentInfos.dataRef.children = newArr;
      this.setState({currentInfos});
    }
  }

  //添加部门输入框
  inputChange = (index, e) => {
    const currentInfos = {...this.state.currentInfos};
    currentInfos.dataRef.children[index].title = e.target.value;
    this.setState({currentInfos});
  }


  //添加部门
  addItem = () => {
    const currentInfos = {...this.state.currentInfos};
    if (!currentInfos.dataRef.children) {
      currentInfos.dataRef.children = [];
    }
    currentInfos.dataRef.children.push(
      {
        key: "",
        title: "",
      }
    );
    this.setState({currentInfos});
  }


  //提交 添加部门
  handleSubmit = (e) => {
    e.preventDefault();
    const {dataRef: {key, children}} = this.state.currentInfos;
    //移除标题为空的选项
    const submitArr = reverseObj(children.filter(val => val.title.length !== 0));
    const submitData = {
      parentDepartId: key,
      comDeparts: submitArr,
    };
    this.systemComDepartBatchInsertDepart(submitData, children, key);
  }

  //树形结构 动态加载数据
  onLoadData = (treeNode) => {
    console.log(treeNode);
    let {key, children} = treeNode.props.dataRef;
    return new Promise((resolve) => {
      const treeData = JSON.parse(JSON.stringify(this.state.treeData));

      if (treeNode.props.children) {
        resolve();
        return;
      }
      systemComDepartList({parentDepartId: treeNode.props.dataRef.key}).then(
        ({data}) => {
          treeNode.props.dataRef.children = changeObj(data);
          this.setState({
            treeData: [...this.state.treeData],
          }, () => {
            console.log(this.state.treeData);
            this.setState({expandedKeys: treeNode.props.dataRef.key});
          });
          resolve();
        },
        (err) => {
          console.log(err);
          resolve();
        }
      );
    });
  }

  onSelect = (selectedKeys, info) => {
    console.log('selected', selectedKeys, info);
    //选中时候，传入当前节点数据
    this.setState({
      currentInfos: {selectedKeys, dataRef: bcx_utils.jsoncopy(info.node.props.dataRef)},
      currentNode: info.node
    });
  }

  /******************************render******************************/


  renderTreeNodes = (data) => {
    return data.map((item) => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode {...item} dataRef={item}/>;
    });
  }

  renderFormItems = () => {
    if (!this.state.currentInfos.dataRef.children) {
      return;
    }
    const formItems = this.state.currentInfos.dataRef.children.map((val, key) => {
      return (
        <div key={key}>
          <div className="item">
            <div className="l">
              <span className="ant-form-item-required">类型:</span>
            </div>
            <Select disabled={true} defaultValue="1" className="select">
              <Option value="1">部门</Option>
            </Select>
            <Icon
              className="dynamic-delete-button"
              type="minus-circle-o"
              onClick={() => this.remove(key, val)}/>
          </div>
          <div className="item">
            <div className="l">
              <span className="ant-form-item-required">类型:</span>
            </div>
            <Input placeholder="请输入"
                   className="r"
                   defaultValue={val.title}
                   value={val.title}
                   onChange={this.inputChange.bind(this, key)}/>
          </div>

        </div>
      )
        ;
    });


    return formItems;
  }

  render() {
    const {currentInfos} = this.state;
    //自身迭代节点
    const loop = data => data.map((item) => {
      const title = <span>{item.key}</span>;
      if (item.children) {
        return (
          <TreeNode key={item.key} title={title}>
            {loop(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.key} title={title}/>;
    });

    return (
      <Container>
        <header className="password-header">组建部门机构</header>
        <div className="department-content">
          <div className="department-inquiry">
            <Tree
              loadData={this.onLoadData}
              onSelect={this.onSelect}
              defaultExpandedKeys={["-1"]}
              defaultSelectedKeys={["-1"]}
            >
              {this.renderTreeNodes(this.state.treeData)}
            </Tree>
          </div>
          <div className="department-right">
            <p className="department-title" style={{marginBottom: 24}}>{currentInfos.dataRef.title}</p>
            {this.renderFormItems()}
            <div style={{paddingLeft: 102}}>
              <Button type="dashed" onClick={this.addItem} style={{width: 337, margin: "0 0 24px 0"}}>
                <Icon type="plus"/> 添加
              </Button>
            </div>
            <div style={{paddingLeft: 102}}>
              <Button style={{marginRight: "8px"}}>取消</Button>
              <Button className="submit" type="primary" onClick={this.handleSubmit}>确定</Button>
            </div>
          </div>
        </div>
      </Container>
    );
  }
}

/*********************样式*************************** */
const
  Container = style.div`{

    .password-header{
        font-size: 20px;
        color: #333333;
        padding-bottom:16px;
        border-bottom:1px solid #e9e9e9;
    }
    .ant-btn-primary{
        background-color: #0F71FF;
    }
    .ant-menu-submenu > .ant-menu{
        background:#fff;
    }
    .department-content{
        min-height: 600px;
        background: #fff;
        border-radius: 5px;
        padding-left: 220px;
        position: relative;
        .department-inquiry{
          width: 220px;
          padding: 16px 8px;
          position: absolute;
          top: 0;
          left: 0;
          input{
            color: #333;
          }
          .depart-menu{
            span{
              color: #333;
              font-size: 14px;
            }
            ul li{
              color: #333;
              font-size: 14px;
            }
          }
        }
        .department-right{
            margin-left:1px;
            padding:24px;
            border-left:1px solid #eee;
            min-height:600px;
            .department-title{
                font-size: 16px;
                color: #333333;
            }
        }
      }
    .item{
      width:440px;
      margin-bottom:24px;
      .dynamic-delete-button {
        cursor: pointer;
        position: absolute;
        font-size: 24px;
        color: #d9d9d9;
        transition: all .3s;
        margin:5px 0 0 10px;
     }
     .dynamic-delete-button:hover {
        color: #777;
     }
     .dynamic-delete-button[disabled] {
        cursor: not-allowed;
        opacity: 0.5;
     }
      >div{
       display:inline-block;
      }
      .l{
        width:94px;
        text-align: right;
        margin-right: 8.3px;
      }
      .r{
        width:337px;
      }
      .select{
       width:304px;
      }
    }  
}`;
